package com.coder4j.javafx;

import com.coder4j.utils.SpringContextUtils;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;

/**
 * 页头
 * @author keller
 * @date 2024-9-5 09:35:15
 */
public class MyHeader {
    private double xOffset = 0;
    private double yOffset = 0;
    public Pane init(final Stage stage) {
        BorderPane root = new BorderPane();


        setDraggable(root,stage);
        root.setPadding(new Insets(10,10,10,10));

        root.setLeft(initLeft());

        root.setRight(initRight(stage));

        return root;
    }

    /**
     * 左侧Logo和标题
     * @return
     */
    private Pane initLeft(){
        HBox box = new HBox();

        ImageView icon = new MyImageViewFactory().init("icon.png").fitWidth(32).radius(32, 32, 8).build();
        MyLabel title = new MyLabel("AI训练测试").color("#000000").fontSize(24);

        box.getChildren().addAll(icon,title);
        box.setSpacing(8);
        return box;
    }

    /**
     * 右侧控制按钮
     * @param stage
     * @return
     */
    private Pane initRight(final Stage stage){
        HBox box = new HBox();

        MyLabel minButton = new MyLabel("-").fontSize(18).color("#000000").addClickListener(event -> stage.setIconified(true));

        //点击关闭按钮，同时关闭窗口和服务
        MyLabel closeButton = new MyLabel("x").fontSize(18).color("#000000").addClickListener(event -> {
            stage.close();
            ApplicationContext context = SpringContextUtils.getApplicationContext();
            int exit = SpringApplication.exit(context, () -> 0);
            System.exit(exit);
        });

        box.setSpacing(20);

        // 添加按钮到顶部区域
        box.getChildren().addAll(minButton, closeButton);
        return box;
    }

    /**
     * 支持拖拽
     * @param node
     * @param stage
     */
    private void setDraggable(Node node, final Stage stage) {
        node.setOnMousePressed(event -> {
            xOffset = event.getSceneX();
            yOffset = event.getSceneY();
        });

        node.setOnMouseDragged(event -> {
            stage.setX(event.getScreenX() - xOffset);
            stage.setY(event.getScreenY() - yOffset);
            stage.setOpacity(0.8f);
        });

        node.setOnDragDone(event -> {stage.setOpacity(1.0f);});

        node.setOnMouseReleased(event -> stage.setOpacity(1.0f));
    }

}
